import {
	mapState
} from 'vuex'

import {
	ASSETS_ROOT,
	IS_ENV_MP,
} from '@/config/env.js'

import routesConfig from '@/plugin/routes.js'
let routePathMap = routesConfig.routePathMap;
let tabBarList = routesConfig.tabBarList;

console.warn('mixin 所有路由页面 routePathMap', JSON.parse(JSON.stringify(routePathMap)))
console.warn('mixin 所有tabbar页面 tabBarList', tabBarList)

export default {
	data() {
		return {
			assetsRoot: ASSETS_ROOT,
			demo: require('@/static/demo.jpg'),
			allowRequestApi: true, //使用允许调用接口
			customShareInfo: {
				title: '', //小程序分享标题 如需自定义 再 对应的页面.vue文件设置标题 示例值  新闻标题
				path: '', //小程序分享路径  如需自定义 再 对应的页面.vue文件设置标题 示例值 /pages/index/index
				imageUrl: '', //分享图片
				query: '', //分享到朋友圈的自定义参数 页面路径 ? 后面的参数
			},
			is_env_mp: IS_ENV_MP == 1, //是否小程序环境
		}
	},
	computed: {
		...mapState([
			//配置
			'vuex_user',
			'vuex_config',
			'vuex_is_login',
			"vuex_huobi",
			'vuex_avatar_default',
			"vuex_cart_number",
			//
			'userInfo',
		]),
		//用户状态
		mix_is_open_weixin_audit_limit() { //是否开启 微信审核限制 开启后可以动态隐藏 审核时无法通过的内容
			return this.vuex_config.site_address == '1'
		},
		mix_is_set_phone() { //是否绑定手机号
			return this.vuex_user.ifNeedBindPhone != 1;
		},
		mix_is_set_avatar_nick() { //是否完善头像昵称
			return !!this.vuex_user.image;
		},

		//用户资料
		mix_user_phone() {
			return this.vuex_user.phone || "";
		},
		mix_user_mobile() {
			return this.vuex_user.phone || "";
		},
		mix_user_avatar() {
			return this.vuex_user.image || this.vuex_avatar_default;
		},
		mix_user_origin_avatar() {
			return this.vuex_user.image;
		},
		mix_user_name() {
			return this.vuex_user.realName || "";
		},
		mix_user_nick() {
			return this.vuex_user.nickname || "";
		},
	},


	filters: {
		formatDate(dateStr) {
			return (dateStr || '').substr(0, 10)
		}
	},

	// 定义全局分享
	// 1.发送给朋友
	onShareAppMessage(res) {
		let site_name = this.vuex_config.comTitle
		let site_logo = this.vuex_config.comLogo


		let {
			title,
			path,
			imageUrl,
			query
		} = this.customShareInfo;
		path = path || '/pages/index/index';


		debugger
		//如果query 为对象格式
		var query_str = '';
		if (typeof query == 'object') {
			var query_arr = []
			for (var key in query) {
				query_arr.push(`${key}=${query[key]}`)
			}
			query_str = query_arr.join('&')
			query = query_str;
		}
		//如果query 为对象格式


		let userId = uni.getStorageSync('userId') || '';
		if (userId) {
			if (query) {
				query = query + '&invite_id=' + userId
			} else {
				query = 'invite_id=' + userId
			}
			// if (path.includes('?')) {
			// 	path = path + '&invite_id=' + userId
			// } else {
			// 	path = path + '?invite_id=' + userId
			// }
		}

		if (query) {
			path = path + '?' + query
		}



		let info = {
			title: title || site_name || '',
			path: path,
			imageUrl: imageUrl || site_logo || '',
		}
		console.warn('分享配置', info)

		return info
	},
	//2.分享到朋友圈
	onShareTimeline(res) {

		let site_name = this.vuex_config.comTitle
		let site_logo = this.vuex_config.comLogo

		let {
			title,
			path,
			imageUrl,
			query
		} = this.customShareInfo;


		//如果query 为对象格式
		var query_str = '';
		if (typeof query == 'object') {
			var query_arr = []
			for (var key in query) {
				query_arr.push(`${key}=${query[key]}`)
			}
			query_str = query_arr.join('&')
			query = query_str;
		}
		//如果query 为对象格式


		let userId = uni.getStorageSync('userId') || ''
		if (userId) {
			if (query) {
				query = query + '&invite_id=' + userId
			} else {
				query = 'invite_id=' + userId
			}
		}

		let info = {
			title: title || site_name || '',
			query: query,
			imageUrl: imageUrl || site_logo || '',
		}

		console.warn('分享配置', info)

		return info
	},

	methods: {
		/**
		 * @param {Object} localPath
		 * 处理本地图片资源过大问题 
		 * 资源放置服务器  引入本地资源 改为 引入网络图片资源
		 * 示例：  src="@/static/static-online/about/about-bg.png"  改为
		 * getAssets('@/static/static-online/about/about-bg.png')
		 * 对应服务器上 /mpassets/static/static-online/about/about-bg.png
		 */
		getAssets(localPath) {
			let onlinePath = localPath.replace('@/static/static-online/', 'static-online/')


			// return this.assetsRoot + 'big-file/' + onlinePath
			// 域名 + /mpassets/ + static-online/...
			return this.assetsRoot + onlinePath
		},

		/**
		 * 登录状态检测  未登录需要跳转登录页
		 * 	if(!this.mix_checkLogin()) {
					return
				}
		 */




		mix_checkLogin() {
			let loginStatus = true;
			if (!this.vuex_is_login) {
				// this.$alert('请您先登录')
				// setTimeout(() => {
				// 	this.toRoute('/login')
				// }, 1000)

				uni.showModal({
					title: "信息提示",
					content: '您尚未登录，是否去登录?',
					confirmText: "确定",
					showCancel: true,
					success: (res) => {
						if (res.confirm) {
							this.toRoute('/login')
						}
					}
				});

				loginStatus = false;
			}

			return loginStatus
		},


		// 设置分享信息
		setCustomShareInfo(info) {
			this.customShareInfo = {
				title: '', //小程序分享标题 如需自定义 再 对应的页面.vue文件设置标题 示例值  新闻标题
				path: '', //小程序分享路径  如需自定义 再 对应的页面.vue文件设置标题 示例值 /pages/index/index
				imageUrl: '', //分享图片
				query: '', //分享到朋友圈的自定义参数 页面路径 ? 后面的参数

				...info
			}

			// this.customShareInfo  = {...info}
		},


		// 处理路由跳转参数
		handleRoutePathQuery(path) {
			let new_path = '';
			let new_query = '';
			let query = {}

			// debugger

			if (path.includes('?')) {
				let path_arr = path.split('?')
				new_path = path_arr[0]
				let queryStr = path_arr[1]

				if (queryStr) {
					var group_arr = queryStr.split('&');
					group_arr.forEach(key_and_val => {
						var key_val_arr = key_and_val.split('=');
						var key = key_val_arr[0]
						var val = key_val_arr[1]
						query[key] = val
					})
				}
			} else {
				new_path = path
			}

			if (new_path.includes('/')) {
				let new_path_arr = new_path.split('/')
				new_path = new_path_arr[new_path_arr.length - 1];
			}



			return {
				path: new_path,
				query: query,
			}
		},


		toRedirect(option) {
			let info = this.handleRoutePathQuery(option);
			let path = info.path
			let query = info.query
			this.toRoute({
				path: path,
				query: query,
				mode: 'redirectTo'
			})
		},

		toRoute(option) {
			let paramstype = typeof option;
			let path = '';
			let query = '';
			let mode = '';

			if (paramstype == 'string') {
				path = option;
				let info = this.handleRoutePathQuery(path);
				path = info.path
				query = info.query
			} else if (paramstype == 'object') {
				path = option.path || '';
				query = option.query || {};
				mode = option.mode || '';
			}

			path = path.replace('/', '')


			let tabbars = tabBarList || []; // ['index', 'my', 'routes', ];
			let isTabbarPage = tabbars.includes(path);


			if (this.allowPageToggleTimeForToRoute) {

			}
			//1
			// if (!this.vuex_is_login && auth_pages.includes(path)) {
			// 	console.log('mixin toPage 未登录下权限页面重定向')

			//1 需要登录访问的页面
			//2 跳转tabbar页面
			//3 跳转主包内普通页面


			let routeItem = routePathMap[path];
			if (!routeItem) {
				console.log('path', path)
				this.$alert('没有查询到当前跳转路由' + path)
				return
			}


			let auth_pages = [
				'my-info',
				// 'order-submit',
				'order-list',
			]

			if (!this.vuex_is_login) {
				if (auth_pages.includes(path)) {
					// this.toRoute({
					// 	path: '/login',
					// 	mode: 'redirectTo'
					// })
 
					uni.showModal({
						title: "温馨提示",
						content: '您尚未登录，是否去登录?',
						confirmText: "确定",
						showCancel: true,
						success: (res) => {
							if (res.confirm) {
								// this.toRoute('/login')
								this.toRoute({
									path: '/login',
									mode: 'redirectTo'
								})
							}
						}
					})

					return
				}
			}


			let realpath = '/' + routeItem.route;


			let queryKeys = Object.keys(query);
			let queryStr = '';
			let queryArr = [];
			if (queryKeys.length) {
				for (var key in query) {
					queryArr.push(key + '=' + query[key])
				}
			}
			queryStr = queryArr.join('&');

			if (isTabbarPage) {
				queryStr = ''
			}

			if (queryStr) {
				realpath = realpath + '?' + queryStr
			}


			if (mode && !isTabbarPage) {
				//mode = navigateTo  switchTab  redirectTo  reLaunch 
				// if (mode == 'reLaunch') {
				// 	realpath = realpath.replace('/', '');
				// }
				console.log('toRoute mode', mode)
				console.log('toRoute realpath', realpath)

				uni[mode]({
					url: realpath
				});
			} else if (isTabbarPage) {
				//可能出现tabbar带参数的场景
				//例如首页自定义模块需要跳转到分类页面并携带分类id场景
				if (queryKeys.length) {
					this.$store.commit('set_cache_tabbar_query', query)
				}
				uni.switchTab({
					url: realpath
				});
			} else {
				uni.navigateTo({
					url: realpath
				});
			}
		},

		toBack(option = {}) {
			debugger
			let time = option.time || 0; //延迟多少毫秒执行
			let delta = option.delta || 1; //返回的层数

			console.log('mixin toBack 跳转路由');
			var pages = getCurrentPages();
			var page = pages[pages.length - 1];
			console.log('toBack pages', pages)
			console.log('toBack page', page)

			if (pages.length > 1) {
				if (time) {
					setTimeout(() => {
						uni.navigateBack({
							delta: delta
						})
					}, time)
				} else {
					uni.navigateBack({
						delta: delta
					})
				}
			} else {
				if (time) {
					setTimeout(() => {
						this.toRoute('index')
					}, time)
				} else {
					this.toRoute('index')
				}
			}
		},

		toIndex() {
			this.toRoute({
				path: '/index',
				mode: 'redirectTo'
			})
		},
		toReLaunchIndex() {
			this.toRoute({
				path: '/index',
				mode: 'reLaunch'
			})
		},
		toReLaunchLogin(query = {}) {
			this.toRoute({
				path: '/login',
				mode: 'reLaunch',
				query: query
			})
		},


		// 阻止点击事件冒泡
		clickStop() {

		},
		// 全局函数节流 - 例如 点击按钮提交表单
		mix_throttle(func, wait = 1500, immediate = true) {
			// uni.$u.throttle(func, 1500, true)
			uni.$u.throttle(func, wait, immediate)
		},
		// 全局函数防抖 - 例如 输入内容时搜索
		mix_debounce(func, wait = 500, immediate = false) {
			// uni.$u.debounce(func, 500, false)
			uni.$u.debounce(func, wait, immediate)
		},


		// 处理小程序跳转 例如 后台录入了  自定义Url 
		//如 /pages/goods/detail?id=1
		//特殊 /pages/goods/detail?id=1&title=
		handleUrlJump(url) {
			// debugger
			//.split('?')[0]
			// let url_arr = url.split('/');
			let url_group = url.split('?');
			let url_left_path = url_group[0];
			let url_right_query = url_group[1];

			//
			let url_left_arr = url_left_path.split('/')
			let path = '/' + url_left_arr[url_left_arr.length - 1]; //得到路径path

			//
			// let route_arr = fullpath.split('?');
			// let path = route_arr[0];
			let query = {};
			if (url_right_query) {
				var items = url_right_query.split('&')
				items.forEach(key_value => {
					let arr = key_value.split('=')
					let key = arr[0]
					let value = arr[1]

					query[key] = value
				})
			}
			console.log('handleUrlJump path', path)
			console.log('handleUrlJump query', query)
			this.toRoute({
				path: path,
				query: query
			})
		},


		// redirectTo(path) {
		// 	console.log('mixin 跳转路由')
		// 	uni.redirectTo({
		// 		url:'/pages/' + path
		// 	})
		// },

		showLoading(option = {}) {
			uni.showLoading({
				title: option.title || '加载中',
				mask: true,
			});
			if (option.disClose) {

			} else {
				setTimeout(function() {
					uni.hideLoading();
				}, 2000);
			}
		},
		hideLoading(time) {
			if (time) {
				setTimeout(() => {
					uni.hideLoading();
				}, time)
			} else {
				uni.hideLoading();
			}
		},
	}
}